from flask import Flask, request, jsonify
from flask_restful import Api, Resource
from models import db, Message
from config import Config

app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
api = Api(app)

class MessageResource(Resource):
    def get(self, message_id=None):
        if message_id:
            message = Message.query.get_or_404(message_id)
            return jsonify(message.to_dict())
        else:
            messages = Message.query.all()
            return jsonify([message.to_dict() for message in messages])

    def post(self):
        data = request.json
        new_message = Message(title=data['title'], content=data['content'])
        db.session.add(new_message)
        db.session.commit()
        return jsonify(new_message.to_dict()), 201

    def put(self, message_id):
        message = Message.query.get_or_404(message_id)
        data = request.json
        message.title = data.get('title', message.title)
        message.content = data.get('content', message.content)
        db.session.commit()
        return jsonify(message.to_dict())

    def delete(self, message_id):
        message = Message.query.get_or_404(message_id)
        db.session.delete(message)
        db.session.commit()
        return '', 204

api.add_resource(MessageResource, '/messages', '/messages/<int:message_id>')

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(host='0.0.0.0', port=3001, debug=True)